
import 'dart:async';

import 'package:bookshelf/entity/book_entity.dart';
import 'package:bookshelf/http/api.dart';
import 'package:bookshelf/util/toast_util.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../entity/setting_entity.dart';
import '../entity/up_request_entity.dart';
import '../event/inventory_event.dart';
import '../log/logger.dart';
import '../main.dart';
import '../socket/send_helper.dart';
import '../socket/socket_helper.dart';
import '../widget/app_bar.dart';


class Straighten extends StatefulWidget {
  const Straighten({Key? key}) : super(key: key);

  @override
  State<Straighten> createState() => _StraightenState();
}

class _StraightenState extends State<Straighten> {

  final List<BookEntity> _list = [];
  final RxList<BookEntity> _filterList = RxList();
  var total = 0.obs;
  // $3  0=待盘点 1=盘点中 2=盘点完成
  List<SettingEntityReader> readers = [];
  StreamSubscription? inventorySubscription;

  int blockIndex = 0;
  int inventoryIndex = 0;

  bool isFinish = false;
  
  RxBool correct = RxBool(true);
  RxBool wrong = RxBool(true);
  RxBool lose = RxBool(true);
  RxBool news = RxBool(true);

  @override
  initState() {
    super.initState();

    if(settingEntity.reader != null){
      for (var element in settingEntity.reader!) {
        if(element.state == 0){
          readers.add((element));
        }
      }
    }
    //盘点回调
    inventorySubscription = eventFactory.on<InventoryEvent>().listen((event) {
      for (var element in event.data) {
        try{
          var currentPlace = settingEntity.place!.firstWhere((e) => (e.readerAddr == element.$3)
              && (e.ant!.padLeft(2,'0') == int.parse(element.$2,radix: 16).toString().padLeft(2,'0'))).place;
          BookEntity? entity = _list.firstWhereOrNull((e) => e.uid == element.$1);
          if(entity != null){

            entity.place = currentPlace;
            entity.placeName = _analyzePlace(currentPlace);
            if(currentPlace  == entity.placeFirst){
              entity.status = 0;
            }else{
              entity.status = 2;
              Logger().write('uid = ${element.$1}  placeFirst = ${entity.placeFirst} currentPlace = $currentPlace, ${currentPlace == entity.placeFirst}\r\n');
            }
          }else{
            _list.add(BookEntity()
              ..uid = element.$1
              ..place = currentPlace
              ..placeName = _analyzePlace(currentPlace)
              ..status = 1
            );
          }
        }catch(e){
          Logger().write('uid = ${element.$1},ant = ${element.$2}, error =  $e \r\n');
        }
      }
      inventoryIndex++;
      _inventory();
    });

    _queryBook();
  }

  _queryBook() async {
    BotToast.showLoading(clickClose: true);
    var list = await query('${settingEntity.roomNo}${settingEntity.columnNo}');
    if(list != null){
      for (var element in list) {
        _list.add(element
          ..status = -1
          ..place = null
          ..placeName = null
        );
      }
    }
    _inventory();
  }

  //开始盘点
  _inventory(){
    if(readers.isNotEmpty ){
      if(inventoryIndex<readers.length){
        SocketHelper socketHelper = SocketHelper(readers[inventoryIndex].readerAddr!, int.tryParse(readers[inventoryIndex].readerPort!)??8899);
        Future.delayed(const Duration(seconds: 1),(){
          socketHelper.sendData(inventoryAll());
        });
      }else{
        isFinish = true;
        _filterList.addAll(_list);
        total.value = _filterList.length;
        BotToast.closeAllLoading();
      }
    }
  }


  @override
  void dispose() {
    inventorySubscription?.cancel();
    inventorySubscription = null;
    super.dispose();
  }


  _title(){
    return Container(
      margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: (){
              Get.back();
            },
            child: Image.asset("assets/images/back.png",width:40.w,fit: BoxFit.fitWidth,),
          ),
          Text("顺架清单",style: TextStyle(color: Colors.white,fontSize: 12.sp,fontWeight: FontWeight.bold),),
          Obx(() => Text("总量:${total.value}",style: TextStyle(color: const Color.fromRGBO(51, 226, 255, 1),fontSize: 8.sp),))
        ],
      )
    );
  }

  _divider(){
    return Divider(
      height: 0.5.h,
      indent: 4.w,
      endIndent: 4.w,
      color: const Color.fromRGBO(56, 141, 255, 1),
    );
  }

  _listLabel(){
    return Container(
      padding: EdgeInsets.only(top: 5.h,bottom: 5.h),
      child: Row(
        // mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _label('UID',75.w,),
          _label('图书名称',75.w),
          _label('初始位置',85.w),
          _label('当前位置',85.w),
          _label('状态',45.w),
        ],
      )
    );
  }

  _label(text,width){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: const Color.fromRGBO(55, 112, 173, 1),fontSize: 8.sp),textAlign: TextAlign.center,),
    );
  }

  _item(text,width,{Color color = Colors.black}){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: color,fontSize: 6.sp),textAlign: TextAlign.center,),
    );
  }


  _itemBuilder(index){
    var item = _filterList[index];
    return Container(
      padding: EdgeInsets.only(top: 5.h,bottom: 5.h),
      alignment: Alignment.center,
      child: Row(
        children: [
          _item('${item.uid}',75.w),
          _item(item.mainTitle??'',75.w),
          _item(item.firstPlaceName??'',85.w),
          _item(item.placeName??'',85.w),
          _item(item.status==0?'正确在架':item.status==1?'本架新增':item.status==2?'错误在架':'缺失在架', 45.w,
              color:item.status==0?Colors.black:item.status==1?const Color.fromRGBO(51, 226, 255, 1):item.status==2?Colors.deepOrangeAccent:Colors.red),
        ],
      )
    );
  }

  _analyzePlace(String? place){
    if(place == null){
      return '';
    }
    // String room = place.substring(0,2);
    String column = place.substring(2,6);
    String side = place.substring(6,8);
    String knot = place.substring(8,10);
    String floor = place.substring(10,12);
    return '${settingEntity.roomName}$column列${side=='01'?'A面':'B面'}$knot节$floor层';
  }

  _filter(){
    _filterList.clear();
    _filterList.addAll(_list);
    if(!correct.value){
      _filterList.removeWhere((element) => element.status == 0);
    }
    if(!wrong.value){
      _filterList.removeWhere((element) => element.status == 2);
    }
    if(!lose.value){
      _filterList.removeWhere((element) => element.status == -1);
    }
    if(!news.value){
      _filterList.removeWhere((element) => element.status == 1);
    }
    total.value = _filterList.length;

  }

  _filterWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Obx(() => Checkbox(
          value: correct.value,
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          onChanged: (data) {
            correct.value = !correct.value;
            _filter();
          },
        )),
        Text("正确在架     ",style: TextStyle(color: Colors.blue,fontSize: 6.sp),),
        Obx(() => Checkbox(
          value: wrong.value,
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          onChanged: (data) {
            wrong.value = !wrong.value;
            _filter();
          },
        )),
        Text("错误在架     ",style: TextStyle(color: Colors.deepOrangeAccent,fontSize: 6.sp),),
        Obx(() => Checkbox(
          value: lose.value,
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          onChanged: (data) {
            lose.value = !lose.value;
            _filter();
          },
        )),
        Text("缺失在架     ",style: TextStyle(color: Colors.red,fontSize: 6.sp),),
        Obx(() => Checkbox(
          value: news.value,
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          onChanged: (data) {
            news.value = !news.value;
            _filter();
          },
        )),
        Text("本架新增     ",style: TextStyle(color: const Color.fromRGBO(51, 226, 255, 1),fontSize: 6.sp),),
      ],
    );
  }

  _booksContainer(){
    return Container(
      margin: EdgeInsets.only(left: 8.w,right: 8.w,top: 10.h),
      width: double.infinity,
      height: 610.h,
      decoration: const BoxDecoration(
        color: Colors.white
      ),
      child: Column(
        children: [
          _filterWidget(),
          _listLabel(),
          _divider(),
          SizedBox(
            height: 520.h,
            child: Obx(() => ListView.separated(
              itemBuilder: (context, index) {
                return _itemBuilder(index);
              },
              itemCount: _filterList.length,
              separatorBuilder: (BuildContext context, int index) {
                return Divider(
                  height: 0.5.h, // Divider 组件高度
                  // thickness: 5, // 分割线线宽，分割线居于 Divider 中心
                  indent: 4.w, // 分割线左侧间距
                  endIndent: 4.w, // 分割线右侧间距
                  color: Colors.grey,
                );
              },
            ),),
          ),
          SizedBox(height: 10.h,),
          InkWell(
            onTap: () async {
              if(!isFinish){
                toastWarn('还未盘点完成。。。。');
              }
              var list  = [];
              var newList  = [];
              for (var element in _list) {
                if(element.status == 0){
                  continue;
                }
                if(element.status == 1){
                  newList.add(UpRequestEntity()
                    ..isfirst = false
                    ..uid = element.uid
                    // ..no = element.no
                    ..placeName = element.placeName
                    ..place = element.place);
                }else{
                  list.add(UpRequestEntity()
                    ..isfirst = true
                    ..uid = element.uid
                    ..no = element.no
                    ..placeName = element.placeName
                    ..place = element.place);
                }

              }
              // BotToast.showLoading();
              if(newList.isNotEmpty){
                up(newList.toString());
              }
              if(list.isNotEmpty){
                up(list.toString());
              }
              // BotToast.closeAllLoading();
              // if(result){
              toastWarn('顺架成功');
              // }
              Get.back();
            },
            child:  Image.asset("assets/images/straighten.png", width:70.w, fit: BoxFit.fitWidth,),
          ),
        ],
      )
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            appBar(),
            _title(),
            _booksContainer(),
          ],
        ),
      ),
    );
  }
}

